//
//  OpenSDK_LoginMoreView.m
//  OpenSDK
//
//  Created by 涂俊 on 2018/7/31.
//  Copyright © 2018年 WYHT. All rights reserved.
//

#import "OpenSDK_LoginMoreView.h"
#import "OpenSDK_LoginLoadingView.h"
#import "OpenSDK_LoginTypeCell.h"
#import "OpenSDK_DataKeys.h"
#import "OpenSDK_DataManager.h"
#import "OpenSDK_UIManager.h"
#import "OpenSDK_LoginManager.h"
#import "OpenSDK_Toast.h"
#import "OpenSDK_UIUtil.h"
#import "OpenSDK_LoginProtocol.h"
#import "OpenSDK_UserAgreementView.h"
#import "OPKTracking.h"
#import "OPKCoreConfiguration.h"

@interface OpenSDK_LoginMoreView () <UICollectionViewDelegate, UICollectionViewDataSource>
// 用户协议视图
@property (unsafe_unretained, nonatomic) IBOutlet OpenSDK_UserAgreementView *userAgreementView;
@property (unsafe_unretained, nonatomic) IBOutlet NSLayoutConstraint *contentViewHeightConstraint;
@property (unsafe_unretained, nonatomic) IBOutlet NSLayoutConstraint *bgImageViewHeightConstraint;
@property (unsafe_unretained, nonatomic) IBOutlet NSLayoutConstraint *collectionViewBottomConstraint;

@end

@implementation OpenSDK_LoginMoreView

{
    NSArray *loginTypesList;
}

static CGFloat const padding = 16;
static CGFloat const insetMargin = 10;
static CGFloat const itemHeight = 28;

#pragma mark - 生命周期函数
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    _bgView.backgroundColor = UIColor.whiteColor;
    _bgView.layer.cornerRadius = 10;
    _bgView.layer.masksToBounds = true;
    self.loginTypesView.delegate = self;
    self.loginTypesView.dataSource = self;
    [self.loginTypesView registerNib:[UINib nibWithNibName:@"OpenSDK_LoginTypeCell" bundle:nil] forCellWithReuseIdentifier:@"OpenSDK_LoginTypeCell"];
    
    NSMutableArray *supportTypes = [OpenSDK_DataManager getInstance].supportLoginTypes.mutableCopy;
    
    NSString *oneKey = OpenSDK_S_ONE_KEY;
    if ([supportTypes containsObject:oneKey]) {
        id<OpenSDK_LoginProtocol> sdk = [[OpenSDK_DataManager getInstance].supportSDKServerNames objectForKey:oneKey];
        if ([sdk status] == 1) { // 预登陆失败，则不显示
            [supportTypes removeObject:oneKey];
            [OpenSDK_DataManager getInstance].supportLoginTypes = supportTypes.copy;
        }
    }
    loginTypesList = supportTypes.copy;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    // 设置对勾按钮状态
    [_userAgreementView.agreeButton setSelected:[OpenSDK_DataManager getInstance].contranctChecked];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [[OPKTracking shared] pageView:OPKPageLoginOther];
}

// 用户协议相关检查
- (BOOL)contranctChecked {
    if ([OpenSDK_DataManager getInstance].showContranct == NO) {
        return YES;
    }
    // 是否已经同意用户协议
    if (_userAgreementView.agreeButton.isSelected == NO) {
        [[[OpenSDK_iToast makeText:@"请先同意相关政策条款再登录"] setDuration:2000] show];
        return NO;
    }
    return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - btn callback
- (IBAction)didClickBackBtn:(id)sender {
    if (self.navigationController.viewControllers.count > 1) {
        [self.navigationController popViewControllerAnimated:NO];
    } else {
        [[OpenSDK_UIManager getInstance] closeUI];
    }
}


#pragma mark - 支付列表回调函数
//定义展示的Section的个数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

//定义展示的UICollectionViewCell的个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return [loginTypesList count];
}

//每个UICollectionView展示的内容
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"%@,%@",NSStringFromClass([self class]), NSStringFromSelector(_cmd));
    OpenSDK_LoginTypeCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"OpenSDK_LoginTypeCell" forIndexPath:indexPath];
    NSString *loginType = [loginTypesList objectAtIndex:indexPath.row];
    if ([OpenSDK_S_ACCOUNT isEqualToString:loginType]) {
        cell.backgroundImageView.image = [UIImage imageNamed:@"op_login_type_pwd_n_bg"];
        cell.iconView.image = [UIImage imageNamed:@"op_login_type_pwd"];
        cell.nameView.text = @"密码登录";
        cell.nameView.textColor = [UIColor blackColor];
    } else if ([OpenSDK_S_DYNAMIC isEqual:loginType]) {
        cell.backgroundImageView.image = [UIImage imageNamed:@"op_login_type_dy_n_bg"];
        cell.iconView.image = [UIImage imageNamed:@"op_login_type_n_dy"];
        cell.nameView.text = @"手机验证码";
        cell.nameView.textColor = [UIColor whiteColor];
    } else if ([OpenSDK_S_TEMPORARY isEqual:loginType]){
        cell.backgroundImageView.image = [UIImage imageNamed:@"op_login_type_temp_n_bg"];
        cell.iconView.image = [UIImage imageNamed:@"op_login_type_temp"];
        cell.nameView.text = @"游客登录";
        cell.nameView.textColor = [UIColor whiteColor];
    }else {
        id<OpenSDK_LoginProtocol> sdk = [[OpenSDK_DataManager getInstance].supportSDKServerNames objectForKey:loginType];
        cell.backgroundImageView.image = [UIImage imageNamed:[sdk getBackgroundImage]];
        cell.iconView.image = [UIImage imageNamed:[sdk getDisplayIcon]];
        cell.nameView.text = [sdk getDisplayName];
        if ([loginType isEqual:@"AppleLogin"]) {
            cell.nameView.textColor = [UIColor blackColor];
        } else {
            cell.nameView.textColor = [UIColor whiteColor];
        }
    }
    return cell;
}

//定义每个UICollectionView 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
//    CGFloat width = (self.loginTypesView.frame.size.width - [OpenSDK_UIUtil getUISize:padding]) / 2.0 - 1;
    CGFloat width = (self.loginTypesView.frame.size.width - padding) / 2.0 - 1;
    NSLog(@"collectionView insetForSectionAtIndex! cvWidth=%f, itemWidth=%f", self.loginTypesView.frame.size.width, width);
    return CGSizeMake(width, itemHeight);
}

//设置整个组的缩进量是多少
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsZero;
}

//设置最小行间距，也就是前一行与后一行的中间最小间隔
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
//    return [OpenSDK_UIUtil getUISize:insetMargin];
    return insetMargin;
}

//设置最小列间距，也就是左列与右一列的中间最小间隔
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
//    return [OpenSDK_UIUtil getUISize:padding];
    return padding;
}

//UICollectionView被选中时调用的方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"collectionView click! index=%ld", (long)indexPath.row);
    
    NSString *loginType = [loginTypesList objectAtIndex:indexPath.row];
    if ([OpenSDK_S_ACCOUNT isEqualToString:loginType]) {
        //邮箱登录界面
        [self didClickBackBtn:nil];
        // 统计
        [[OPKTracking shared] event:OPKEventLoginPassword];
        [[OpenSDK_UIManager getInstance] showViewControllerWithSBId:@"LoginMain" vcid:@"OpenSDK_LoginMailView"];
    } else if ([OpenSDK_S_DYNAMIC isEqualToString:loginType]) {
        [[OPKTracking shared] event:OPKEventLoginMobile];
        // 手机登录
        [[OpenSDK_UIManager getInstance] showViewControllerWithSBId:@"LoginMain" vcid:@"OpenSDK_LoginMobileView"];
    } else if ([OpenSDK_S_TEMPORARY isEqualToString:loginType]) {
        // 游客登录
        // 先弹出loading框
        UIStoryboard *loginStoryboard = [UIStoryboard storyboardWithName:@"LoginMain" bundle:nil];
        OpenSDK_LoginLoadingView *vc = (OpenSDK_LoginLoadingView *) [loginStoryboard instantiateViewControllerWithIdentifier:@"OpenSDK_LoginLoadingView"];
        vc.accoutnName = @"游客";
        [self.navigationController pushViewController:vc animated:NO];
        // 再调用登录接口
        [[OpenSDK_LoginManager getInstance] loginWithGuest:^(BOOL result, OpenSDK_AccountRecord *account, long errorNo, NSString *err) {
            if (!result) {
                // 登录失败
                [[[OpenSDK_iToast makeText:err] setDuration:2000] show];
            }
            [vc loginResultCallback:result account:account];
        }];
    }
    else if ([OpenSDK_S_ONE_KEY isEqualToString:loginType]) {
//        [[OPKTracking shared] event:OPKEventLoginOneKey];
//        // 是否已经同意用户协议
//        if ([self contranctChecked] == NO) {
//            return;
//        }
//        // loading框
//        UIStoryboard *loginStoryboard = [UIStoryboard storyboardWithName:@"LoginMain" bundle:nil];
//        OpenSDK_LoginLoadingView *vc = (OpenSDK_LoginLoadingView *) [loginStoryboard instantiateViewControllerWithIdentifier:@"OpenSDK_LoginLoadingView"];
//
//        id<OpenSDK_LoginProtocol> sdk = [[OpenSDK_DataManager getInstance].supportSDKServerNames objectForKey:loginType];
//        __block typeof(sdk) weakSdk = sdk;
//        sdk.actionBlock = ^(NSInteger type, NSString *content) {
//            if (type == 8) {
//                [[OPKTracking shared] event:OPKEventLoginOnekeyNext];
//                vc.accoutnName = [weakSdk getDisplaySdkName];
//                [self.navigationController pushViewController:vc animated:NO];
//            }
//        };
//
//        // 再调用第三方登录接口
//        [[OpenSDK_LoginManager getInstance] loginWithPlatform:loginType delegate:^(BOOL result, OpenSDK_AccountRecord *account, long errorNo, NSString *err) {
//            if (!result) {
//                if (errorNo == 6004) {
//                    [[OpenSDK_UIManager getInstance] closeUI];
//                    return;
//                }
//                // 登录失败
//                [[[OpenSDK_iToast makeText:err] setDuration:2000] show];
//            }
//            [vc loginResultCallback:result account:account];
//        }];
        [[OpenSDK_UIManager getInstance] showOneKeyLogin];
    }
    else if ([OpenSDK_S_FACEBOOKSDK isEqualToString:loginType]) {
        // TODO
    } else if ([OpenSDK_S_FACEBOOKSDK_ACCOUNTKIT isEqualToString:loginType]) {
        // TODO
    } else {
        if ([loginType isEqual:@"QQ"]) {
            [[OPKTracking shared] event:OPKEventLoginQQ];
        } else if ([loginType isEqual:@"WeChatLogin"]) {
            [[OPKTracking shared] event:OPKEventLoginWeChat];
        } else if ([loginType isEqual:@"AppleLogin"]) {
            [[OPKTracking shared] event:OPKEventLoginApple];
        }
        // 是否已经同意用户协议
        if ([self contranctChecked] == NO) {
            return;
        }
        id<OpenSDK_LoginProtocol> sdk = [[OpenSDK_DataManager getInstance].supportSDKServerNames objectForKey:loginType];
        // 先弹出loading框
        UIStoryboard *loginStoryboard = [UIStoryboard storyboardWithName:@"LoginMain" bundle:nil];
        OpenSDK_LoginLoadingView *vc = (OpenSDK_LoginLoadingView *) [loginStoryboard instantiateViewControllerWithIdentifier:@"OpenSDK_LoginLoadingView"];
        vc.accoutnName = [sdk getDisplaySdkName];
        [self.navigationController pushViewController:vc animated:NO];
        
        // 再调用第三方登录接口
        [[OpenSDK_LoginManager getInstance] loginWithPlatform:loginType delegate:^(BOOL result, OpenSDK_AccountRecord *account, long errorNo, NSString *err) {
            if (!result) {
                // 登录失败
                [[[OpenSDK_iToast makeText:err] setDuration:2000] show];
            }
            [vc loginResultCallback:result account:account];
        }];
    }
}
@end
